package cacco.jp.mld.panel.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cacco.jp.mld.panel.entity.UserEntity;

@Repository
public class UserDao {
	private static int totalRecords;

	@Autowired
	private SessionFactory sessionFactory;

	@Transactional
	public int add(UserEntity employee) {
		int id = employee.getId();
		this.sessionFactory.getCurrentSession().save(employee);
		id = employee.getId();
		return id;
	}

	@Transactional
	public List<UserEntity> getAll() {
		return this.sessionFactory.getCurrentSession()
				.createQuery("from UserEntity").list();
	}

	@Transactional
	public void delete(Integer id) {
		UserEntity employee = (UserEntity) sessionFactory.getCurrentSession()
				.load(UserEntity.class, id);
		if (null != employee) {
			this.sessionFactory.getCurrentSession().delete(employee);
		}
	}

	@Transactional
	public UserEntity findById(int id) {
		Query query = sessionFactory.getCurrentSession().getNamedQuery(
				"findUserById");
		query.setInteger("id", id);
		UserEntity loginObj = (UserEntity) query.uniqueResult();
		return loginObj;
	}

	@Transactional
	public UserEntity findByUsername(UserEntity loginForm) {
		System.out.println("Hi Dao" + loginForm.getUserName());
		Query query = sessionFactory.getCurrentSession().getNamedQuery(
				"findUserByNamePassword");
		query.setString("user_name", loginForm.getUserName());
		UserEntity loginObj = (UserEntity) query.uniqueResult();
		return loginObj;
	}

	@Transactional
	public UserEntity findByUsername(String userName) {
		Query query = sessionFactory.getCurrentSession().getNamedQuery(
				"findUserByNamePassword");
		query.setString("user_name", userName);
		UserEntity loginObj = (UserEntity) query.uniqueResult();
		return loginObj;
	}

	@Transactional
	public void update(UserEntity user) {
		sessionFactory.getCurrentSession().update(user);
	}

	@Transactional
	public List<UserEntity> getAlByPage(int pageSize, int page, String sidx,
			String sord) {
		List<UserEntity> list = null;
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from UserEntity order by " + sidx + " " + sord);
		totalRecords = query.list().size();
		query.setFirstResult((page - 1) * pageSize);
		query.setMaxResults(pageSize);
		list = (List<UserEntity>) query.list();
		return list;
	}

	public static int getTotalRecords() {
		return totalRecords;
	}
}
